$(function() {
	$("#rejBtn").show();
	$("#editBtn").show();
    $(".compNum").hide();
    $("#submissionDate").hide();
    $("#creationDate").hide();
    $("#approvalDate").hide();
    $("#ctgSelect").css('display','inline-block');
    $("#viewSelect").css('display','inline-block');
});

function load() {
	$('#dataTable')
		.bootstrapTable(
			{
				method : 'get', // 服务器数据的请求方式 get or post
				url : prefix + '/query/listPending', // 服务器数据的加载地址
				cache: false,
				//showRefresh : true,
				//	showToggle : true,
				//locale: "zh-CN",
				locale: "en-US",
				//locale: "ko-KR",
				iconSize : 'outline',
				toolbar : '#exampleToolbar',
				striped : false, // 设置为true会有隔行变色效果
				dataType : "json", // 服务器返回的数据类型
				pagination : true, // 设置为true会在底部显示分页条
				// queryParamsType : "limit",
				// //设置为limit则会发送符合RESTFull格式的参数
				singleSelect : false, // 设置为true将禁止多选
				// contentType : "application/x-www-form-urlencoded",
				// //发送到服务器的数据编码类型
				pageSize : initPageSize, // 如果设置了分页，每页数据条数
				pageNumber : 1, // 如果设置了分页，首页页码
				//search : true, // 是否显示搜索框
				showColumns : false, // 是否显示内容下拉框（选择显示的列）
				sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                uniqueId:"appId",
				queryParams : function(params) {
					return {
						//说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                        pageSize : params.limit,
						pageNum : params.pageNum,
                        // title : $('#searchName').val(),
						orderBy:'create_time desc'
					};
				},
				onPostBody: function () {
					     //改变复选框样式
					     $("#dataTable").find("input:checkbox").each(function (i) {
					         var $check = $(this);
					         if ($check.attr("id") && $check.next("label")) {
					            return;
					         }
					         var name = $check.attr("name");
					         var id = name + "-" + i;
					         var $label = $('<label for="'+ id +'"></label>');
					         $check.attr("id", id).parent().addClass("bella-checkbox").append($label);
					    });
				},
				onClickRow: function(row, $element, field) {
					//$element.addClass("trCurrent");
				},
				onDblClickRow: function(row, $element, field) {
					//maxView(row.appId,row.title)
				},
				onLoadSuccess:function(data){
					wrapper.total = data.total;
					$.ajax({
						url : prefix + "/query/getPendingNotReadCount",
						data:{
							title : $('#searchName').val(),
							isDelete: 'N'
						},
						type : "get",
						success : function(r) {
							if (r.code == 0) {
								window.top.wrapper.total = r.count;
							}
						}
					});
				},
				// //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
				// queryParamsType = 'limit' ,返回参数必须包含
				// limit, offset, search, sort, order 否则, 需要包含:
				// pageSize, pageNumber, searchText, sortName,
				// sortOrder.
				// 返回false将会终止请求
				columns : [
					{
						checkbox : true,
						class:'bella-checkbox',
						width:'30px'
					},
					{
						field : 'appId',
						title : 'ID',
						visible: false
					},
					{
						field : 'appLineId',
						title : 'LineID',
						visible: false
					},
                    {
                        field : '',
                        title : '<i class="fa fa-tag fa-lg fa-lg" aria-hidden="true"></i>',
                        width : '40px',
                        formatter : function(value, row, index) {
                            var e ="<div class='mailMark' style='position:absolute'>"+
                                		"<i  class='fa fa-tag fa-lg fa-lg' data-toggle='dropdown' aria-haspopup='true' style='color:"+row.category+"' aria-expanded='false' aria-hidden='true'></i>"+
										"<ul class='dropdown-menu mark' data-value="+row.appLineId+">"+
                                            "<li class='dropdown-item' data-value='1' data-color='red'><i class='fa fa-tag fa-lg fa-lg' style='color: red;' aria-hidden='true'></i>&nbsp;&nbsp;&nbsp;Urgent</li>"+
											"<li class='dropdown-item' data-value='2' data-color='#0096D6'><i class='fa fa-tag fa-lg fa-lg' style='color: #0096D6;' aria-hidden='true'></i>&nbsp;&nbsp;&nbsp;Important</li>"+
											"<li class='dropdown-item' data-value='3' data-color='green'><i class='fa fa-tag fa-lg fa-lg' style='color: green;' aria-hidden='true'></i>&nbsp;&nbsp;&nbsp;General</li>"+
											"<div class='dropdown-divider'></div>"+
											"<li class='dropdown-item' data-value='0' data-color='#DCDCDC'><i class='fa fa-tag fa-lg fa-lg' style='color: #DCDCDC;' aria-hidden='true'></i>&nbsp;&nbsp;&nbsp;Deselect</li>"+
                            			"</ul>"+
                            		"</div>"
                            return e;
                        }
                    },
					{
						field : 'title',
						title : 'Title',
						// width: '45%',
						formatter : function(value, row, index) {
						    var style = '';
						    if(row.readTime == null){
						        style = "color:#0048BC;font-weight:700;";
						    }
							var e = '<a class="titleTable" index=\''+index+'\' href="#" title=\''+value+'\' style=\''+style+'\'  onclick="showApproval(\'' + row.appId + '\',\'' + row.appLineId + '\',\'' + row.category + '\',\'' + index + '\',\'' + row.readTime + '\',\'' + row.handleType + '\',\'' + row.arbPmtYn + '\')">'+value+'</a> ';
							return e;
						}
					},
					{
						field : 'createUserNm',
						title : 'Author',
						width : '14%',
						formatter : function(value, row, index) {
							var e = '<a href="#" title=\''+value+'\'  onclick="showEmp(\'' + value + '\')">'+value+'</a> ';
							return e;
						}
					},
					{
						field : 'receiptTimeString',
						title : 'Receipt Date',
						width : '16%'
					},
					{
						title : 'Type',
						width : '15%',
						formatter : function(value, row, index) {
							let e = "<span style='font-size:12px'>"+row.urgentTypeString+','+row.handleTypeName+"</span>" ;
							return e;
						}
					} ]
			});
}

function showApproval(appId,appLineId,category,index,readTime,type,arbPmtYn){
	$.ajax({
		url : prefix + "/query/getApproval/"+appId,
		type : "get",
		success : function(r) {
			$("#noSelected").hide();
			$("#selected").show();
			$("#appIdSpan").text(appId);
			$("#appLineIdSpan").text(appLineId);
			$("#detailTopTitle").text(r.title);
			$("#detailAuthor").text(r.createUserNm+'/'+r.createUserJob);
			$("#detailTime").text(r.createTime);
			$("#comNum").text(r.completeNum);
			$("#contentText").text(r.content);
            $(".detailMark").find('>i').css('color', category);
            $(".detailMark").find(".dropdown-menu").data('value',appLineId);

			if(type === '1' || type === '7'){
				if(arbPmtYn == 'Y'){
					$("#arbBtn").show();
				}else{
					$("#arbBtn").hide();
				}
			    $("#apvBtn").show();
			    $("#cstBtn").hide();
			}else if(type ==='2' || type == '4'){
			    $("#apvBtn").hide();
			    $("#arbBtn").hide();
			    $("#cstBtn").show();
			}else if(type ==='3'){
				$("#apvBtn").show();
			    $("#arbBtn").hide();
			    $("#cstBtn").hide();
			}

			if(dataFlag){
			    reLoad(appId);
			}
			else{
				loadApprovalLines(appId);
				$(".fixed-table-loading").remove();
			}
			loadAttachment(r.attachmentList);
			loadContent(r.content);
		},
		complete:function(){
		    if(readTime=='null'){
		        $.ajax({
                    url : prefix + "/readApproval/"+appLineId,
                    type : "put",
                    success : function(r) {
                        // console.log(r.code+':'+r.msg);
                        // console.log($('#dataTable').find('a[index='+index+']').text());
                        $('#dataTable').find('a[index='+index+']').removeAttr( "style" );
                        if(window.top.wrapper.total>0)
                            window.top.wrapper.total--;
                    }
                });
		    }
		    $(".detailBody").show();
		 }
	});
}

function doApproved(){
	let appId = $("#appIdSpan").text();
	let title = $("#detailTopTitle").text();
	let appLineId = $("#appLineIdSpan").text();

    layer.open({
       title:false,
       closeBtn: 0,
       type: 2,
       shade: [0.1, '#393D49'],
       resize:false,
       btn: ['Approved','Cancel'],
       area: ['416px','250px'],
       content: ['/approval/view/showValidateUser/' + appId + '/Approval comment/' + title,'no'],
       yes: function(index, layero){
			if(validateForm(layero)){
				$.ajax({
					url : prefix + "/handle",
					type : "post",
					data:{
							type:'approve',
							appId:appId,
							appLineId:appLineId,
							remark:layero.find("iframe")[0].contentWindow.$("#comment").val()
						},
					success : function(r) {
						if (r.code == 0) {
							asyncRefreshPage();
							layer.close(index);
						} else {
							layer.alert(r.msg)
						}
					},
					error:function (msg) {
						console.log(msg)
					}
				});
			}
	   }
    });
}

function doConsent(){
    let appId = $("#appIdSpan").text();
	let title = $("#detailTopTitle").text();
	let appLineId = $("#appLineIdSpan").text();

    layer.open({
       title:false,
       closeBtn: 0,
       type: 2,
       shade: [0.1, '#393D49'],
       resize:false,
       btn: ['Consent','Cancel'],
       area: ['416px','250px'],
       content: ['/approval/view/showValidateUser/' + appId + '/Consent comment/' + title,'no'],
       yes: function(index, layero){
			if(validateForm(layero)) {
				$.ajax({
					url: prefix + "/handle",
					type: "post",
					data: {
						type: 'consent',
						appId: appId,
						appLineId: appLineId,
						remark: layero.find("iframe")[0].contentWindow.$("#comment").val()
					},
					success: function (r) {
						if (r.code == 0) {
							asyncRefreshPage();
							layer.close(index);
						} else {
							layer.alert(r.msg);
						}
					}
				});
			}
          }
    });
}

function doReject(){
	let appId = $("#appIdSpan").text();
	let title = $("#detailTopTitle").text();
	let appLineId = $("#appLineIdSpan").text();

    layer.open({
       title:false,
       closeBtn: 0,
       type: 2,
       shade: [0.1, '#393D49'],
       resize:false,
       btn: ['Reject','Cancel'],
       area: ['416px','250px'],
       content: ['/approval/view/showValidateUser/' + appId + '/Reason for rejection/' + title,'no'],
       yes: function(index, layero){
			if(validateForm(layero,1)) {
				$.ajax({
					url: prefix + "/handle",
					type: "post",
					data: {
						type: 'reject',
						appId: appId,
						appLineId: appLineId,
						remark: layero.find("iframe")[0].contentWindow.$("#comment").val()
					},
					success: function (r) {
						if (r.code == 0) {
							asyncRefreshPage()
							layer.close(index)
						} else {
							layer.alert(r.msg)
						}
					}
				});
			}
          }
    });
}

function doArb(){
	let appId = $("#appIdSpan").text();
	let title = $("#detailTopTitle").text();
	let appLineId = $("#appLineIdSpan").text();

    layer.open({
       title:false,
       closeBtn: 0,
       type: 2,
       shade: [0.1, '#393D49'],
       resize:false,
       btn: ['Arbitrary decision','Cancel'],
       area: ['416px','250px'],
       content: ['/approval/view/showValidateUser/' + appId + '/Comment for arbitrary decision/' + title,'no'],
       yes: function(index, layero){
			if(validateForm(layero)) {
				$.ajax({
					url: prefix + "/handle",
					type: "post",
					data: {
						type: 'arbi',
						appId: appId,
						appLineId: appLineId,
						remark: layero.find("iframe")[0].contentWindow.$("#comment").val()
					},
					success: function (r) {
						if (r.code == 0) {
							asyncRefreshPage()
							layer.close(index)
						} else {
							layer.alert(r.msg)
						}
					}
				});
			}
          }
    });
}

function editApproval() {
    var currentUserSeq = $('#approvalLinesTable').bootstrapTable('getRowByUniqueId', $('#appLineIdSpan').text()).seq;

    var url = "/approval/view/showEditLineAndText/"+$("#appIdSpan").text()+"/"+currentUserSeq; //转向网页的地址;
    var name = ""; //网页名称，可为空;
    var iWidth = "1008"; //弹出窗口的宽度;
    var iHeight = "670"; //弹出窗口的高度;
    //window.screen.height获得屏幕的高，window.screen.width获得屏幕的宽
    var iTop = (window.screen.height - 30 - iHeight) / 2; //获得窗口的垂直位置;
    var iLeft = (window.screen.width - 10 - iWidth) / 2; //获得窗口的水平位置;
    window.open(url, name, 'height=' + iHeight + ',,innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
}

function refreshTable() {
    $("#dataTable").bootstrapTable('refresh',{silent: true});
}